<?php

namespace app\api\service\admin;

use app\common\library\Auth;

class AuthService
{
    

    // 登录
    public static function login($data)
    {
        if (!is_array($data) || !isset($data['username']) || !isset($data['password'])) {
            return ['code'=>400,'msg'=>'Invalid Parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $auth = Auth::instance();
        $account = $data['username'];
        $password = $data['password'];
        $keeplogin = isset($data['keeplogin']) ? $data['keeplogin'] : 0;
        $keeploginhours = $keeplogin ? 24 : 0; // 保持登录时24小时，否则0小时

        if (!$account || !$password) {
            return ['code'=>400,'msg'=>'Invalid Parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $ret = $auth->login($account, $password, $keeplogin ? $keeploginhours * 3600 : 0);

        if ($ret) {
            $data = $auth->getUserinfo();
            unset($data['username']);
            unset($data['mobile']);
            unset($data['score']);
            unset($data['user_id']);
            return ['code'=>200, 'msg'=>'Login successful', 'state'=>'OK', 'data'=>$data];
        } else {
            return ['code'=>400, 'msg'=>'Login failed', 'state'=>'DATE_INVALID', 'data'=>null];
        }
    }


    // 退出
    public static function logout()
    {
        try {
            $auth = Auth::instance();
            if (!$auth) {
                throw new RuntimeException('Auth service unavailable');
            }
            $auth->logout();
            return ['code'=>200, 'msg'=>'Logout successful', 'state'=>'OK', 'data'=>null];
        } catch (Exception $e) {
            // 简单记录错误日志，实际项目中可使用正式日志系统
            error_log('Logout failed: ' . $e->getMessage());
            return ['code'=>500, 'msg'=>'Logout failed', 'state'=>'ERROR', 'data'=>null];
        }
    }


    // 个人信息
    public static function userinfo()
    {
        $auth = Auth::instance();

        // 检查用户是否已认证
        if (!$auth->isLogin()) {
            return ['code' => 401, 'msg' => 'Unauthorized', 'state' => 'ERROR'];
        }

        // 获取用户信息
        $data = $auth->getUserinfo();
        if (empty($data)) {
            return ['code' => 404, 'msg' => 'User not found', 'state' => 'ERROR'];
        }

        // 明确允许返回的字段（示例，应根据实际需求调整）
        $allowedFields = ['nickname', 'avatar', 'email', 'gender', 'birthday'];
        $filteredData = array_intersect_key($data, array_flip($allowedFields));

        return ['code' => 200, 'msg' => 'OK', 'state' => 'OK', 'data' => $filteredData];
    }

    
}
